<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="800px"
    :before-close="handleClose"
    :close-on-click-modal="false"
    append-to-body
    :title="title"
  >
    <el-form :model="form" ref="formRef" label-width="110px">
      <el-form-item
        label="优惠券名称"
        prop="coupon_name"
        :rules="[{ required: true, message: '请输入优惠券名称', trigger: 'blur' }]"
      >
        <el-input placeholder="请输入" v-model="form.coupon_name"></el-input>
      </el-form-item>

      <el-form-item
        label="优惠券面额"
        prop="coupon_price"
        :rules="[{ required: true, message: '请输入优惠券面额', trigger: 'blur' }]">
        <el-input type="number" placeholder="请输入" v-model="form.coupon_price"></el-input>
      </el-form-item>

      <el-form-item
        label="优惠券描述"
        prop="coupon_desc"
        :rules="[{ required: true, message: '请输入优惠券描述', trigger: 'blur' }]">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入" v-model="form.coupon_desc"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="tx-c">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="confirm" :loading="btnLoading"
        >确认</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { debounce } from "@/util";
import { ApiGetCouponEdit,ApiGetCouponAdd } from "@/api/index.js";
export default {
  components: {
  },
  data() {
    return {
      form: {
        coupon_name: "",
        coupon_price: "",
        coupon_desc: "",
      },
      btnLoading: false,
      dialogVisible: false,
      id: null,
      title: "",
    };
  },

  methods: {
    confirm: debounce(
      function () {
        this.$refs["formRef"].validate(async (valid) => {
          if (valid) {
            this.btnLoading = true;

            try {
              if (this.id) {
                await ApiGetCouponEdit(this.id, this.form);
                this.$message.success("修改成功");
              } else {
                await ApiGetCouponAdd(this.form);
                this.$message.success("添加成功");
              }
              this.handleClose();
              this.$emit("refresh");
            } finally {
              this.btnLoading = false;
            }
          } else return false;
        });
      },
      500,
      true
    ),

    show(row) {
      if (row) {
        this.id = row.id;
        for (const key in this.form) {
          this.form[key] = row[key]
        }
        this.title = "编辑优惠券";
      } else {
        this.id = null;
        this.title = "添加优惠券";
      }
      this.dialogVisible = true;
    },

    handleClose() {
      this.dialogVisible = false;
      this.form = { 
        coupon_name: "",
        coupon_price: "",
        coupon_desc: "",
      };
      this.$nextTick((_) => {
        this.$refs.formRef.clearValidate();
      });
    },
  },
};
</script>

<style></style>
